package pe.edu.upc.xcode.food.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import pe.edu.upc.xcode.food.domain.Categoria;
import pe.edu.upc.xcode.food.domain.Local;
import pe.edu.upc.xcode.food.domain.Restaurant;

import com.google.gson.Gson;




@Controller
public class RestaurantController {	

	private static final String BASE_URL = "http://localhost:8080/FoodService/services/rest/restaurantes/";

	@Autowired
	private RestTemplate restTemplate;
	
	private Gson gson = new Gson();
	
	public RestaurantController() {
		// TODO Auto-generated constructor stub
	}
	@RequestMapping("/restaurant/guardar.htm")
	public ModelAndView initial(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		String view = "main/home";
			
		Restaurant resta=new Restaurant();
		
		String inputNombre = request.getParameter("inputNombre");
		int selectCategoria =   Integer.parseInt(request.getParameter("selectCategoria"));
		String[]ubicaciones = request.getParameterValues("inputUbicacion");
		String inputDescripcion = request.getParameter("inputDescripcion");

		List<Local> locales=new ArrayList<Local>();
		Local l= null;
		
		Date d =new Date();

		for (String ubic : ubicaciones) {
			l= new Local();
			l.setDireccion(ubic);
			l.setEstado("A");
			locales.add(l);
		}

		Categoria objcategoria=new Categoria();
		objcategoria.setCodigo(selectCategoria);
		
		resta.setNombre(inputNombre);
		resta.setCategoria(objcategoria);
		resta.setDescripcion(inputDescripcion);
	    resta.setLocals(locales);
	    resta.setEstado("A");
	    resta.setFecha(d);
	    
	    
	    String json = gson.toJson(resta);
	    restTemplate.postForObject(BASE_URL, json, String.class);
	    
	        
		
		return new ModelAndView(view);

		
	}
	
	@RequestMapping("/restaurant/asociarInitial.htm")
	public ModelAndView asociarInitial(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		return new ModelAndView("restaurant/agregarrestaurant");
	}
	
	@RequestMapping("/restaurant/asociar.htm")
	public ModelAndView asociar(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		return new ModelAndView("restaurant/agregarrestaurant");
	}

	

}
